package q811_subdomainVisits;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    /*
    子域名访问计数
    直接使用暴力hashMap的方式
    拆分域名后从后往前的加上当前域名的访问次数即可
     */
    public List<String> subdomainVisits(String[] cpdomains) {
        List<String> res = new ArrayList<>();
        Map<String, Integer> map = new HashMap<>();
        for (String str : cpdomains) {
            String[] timesAndString = str.split(" ");
            int times = Integer.parseInt(timesAndString[0]);
            String cur = timesAndString[1];
            String[] curCp = cur.split("\\.");
            String prev = curCp[curCp.length - 1];
            map.put(prev, map.getOrDefault(prev, 0) + times);
            for (int i = curCp.length - 2; i >= 0; i--) {
                String combine = curCp[i] + "." + prev;
                map.put(combine, map.getOrDefault(combine, 0) + times);
                prev = combine;
            }
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            res.add(entry.getValue() + " " + entry.getKey());
        }
        return res;
    }
}
